import JSEncrypt from 'jsencrypt'

interface useCameraProp {
  szPluginContainer: string
  appkey: string
  secret: string
  ip: string
  port: string
  layout: string
}
/**
 * 海康威视
 * @param {Object} config - 配置信息
 * @param {string} config.szPluginContainer - 目标容器dom ID
 * @param {string} config.appkey - appkey
 * @param {string} config.secret - secret
 * @param {string} config.ip - ip
 * @param {string} config.port - port
 * @param {string} config.layout - layout
 */
export const useCamera = ({
  szPluginContainer,
  appkey,
  secret,
  ip,
  port,
  layout,
}: useCameraProp) => {
  const getTargetElWH = () => {
    const el: HTMLElement | null = document.getElementById(szPluginContainer)
    if (!el) return { width: 0, height: 0 }
    return {
      width: el.clientWidth,
      height: el.clientHeight,
    }
  }

  let oWebControl: any = null
  let initCount = 0
  let pubKey: any = null
  const initPlugin = () => {
    oWebControl = new window.WebControl({
      szPluginContainer: szPluginContainer, // 指定容器id
      iServicePortStart: 15900, // 指定起止端口号，建议使用该值
      iServicePortEnd: 15900,
      szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11', // 用于IE10使用ActiveX的clsid
      cbConnectSuccess: function () {
        // 创建WebControl实例成功
        oWebControl
          .JS_StartService('window', {
            // WebControl实例创建成功后需要启动服务
            dllPath: './VideoPluginConnect.dll', // 值"./VideoPluginConnect.dll"写死
          })
          .then(
            function () {
              // 启动插件服务成功
              oWebControl.JS_SetWindowControlCallback({
                // 设置消息回调
                cbIntegrationCallBack: () => {
                  // console.log(odata)
                },
              })

              oWebControl
                .JS_CreateWnd(szPluginContainer, getTargetElWH().width, getTargetElWH().height)
                .then(function () {
                  //JS_CreateWnd创建视频播放窗口，宽高可设定
                  init() // 创建播放实例成功后初始化
                })
            },
            function () {
              // 启动插件服务失败
            },
          )
      },
      cbConnectError: function () {
        // 创建WebControl实例失败
        oWebControl = null
        WebControl.JS_WakeUp('VideoWebPlugin://') // 程序未启动时执行error函数，采用wakeup来启动程序
        initCount++
        if (initCount < 3) {
          setTimeout(function () {
            initPlugin()
          }, 3000)
        } else {
          console.log('插件启动失败，请检查插件是否安装！')
        }
      },
      cbConnectClose: function (bNormalClose: any) {
        // 异常断开：bNormalClose = false
        // JS_Disconnect正常断开：bNormalClose = true
        console.log('cbConnectClose')
        oWebControl = null
        console.log('插件未启动，正在尝试启动，请稍候...')
        WebControl.JS_WakeUp('VideoWebPlugin://')
        initCount++
        if (initCount < 3) {
          setTimeout(function () {
            initPlugin()
          }, 3000)
        } else {
          console.log('插件启动失败，请检查插件是否安装！')
        }
      },
    })
  }

  const getPubKey = (callback: ()=>void) => {
    oWebControl
      .JS_RequestInterface({
        funcName: 'getRSAPubKey',
        argument: JSON.stringify({
          keyLength: 1024,
        }),
      })
      .then(function (oData: any) {
        if (oData.responseMsg.data) {
          pubKey = oData.responseMsg.data
          callback()
        }
      })
  }

  function setEncrypt(value: any) {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(pubKey)
    return encrypt.encrypt(value)
  }

  function setWndCover() {
    const { width, height } = getTargetElWH()
    const iWidth = width
    const iHeight = height
    const oDivRect:any = document.querySelector(`#${szPluginContainer}`)?.getBoundingClientRect()

    let iCoverLeft = oDivRect.left < 0 ? Math.abs(oDivRect.left) : 0
    let iCoverTop = oDivRect.top < 0 ? Math.abs(oDivRect.top) : 0
    let iCoverRight = oDivRect.right - iWidth > 0 ? Math.round(oDivRect.right - iWidth) : 0
    let iCoverBottom = oDivRect.bottom - iHeight > 0 ? Math.round(oDivRect.bottom - iHeight) : 0

    iCoverLeft = iCoverLeft > width ? width : iCoverLeft
    iCoverTop = iCoverTop > height ? height : iCoverTop
    iCoverRight = iCoverRight > width ? width : iCoverRight
    iCoverBottom = iCoverBottom > height ? height : iCoverBottom

    oWebControl.JS_RepairPartWindow(0, 0, width + 1, height) // 多1个像素点防止还原后边界缺失一个像素条
    if (iCoverLeft !== 0) {
      oWebControl.JS_CuttingPartWindow(0, 0, iCoverLeft, height)
    }
    if (iCoverTop !== 0) {
      oWebControl.JS_CuttingPartWindow(0, 0, width + 1, iCoverTop) // 多剪掉一个像素条，防止出现剪掉一部分窗口后出现一个像素条
    }
    if (iCoverRight !== 0) {
      oWebControl.JS_CuttingPartWindow(width - iCoverRight, 0, iCoverRight, height)
    }
    if (iCoverBottom !== 0) {
      oWebControl.JS_CuttingPartWindow(0, height - iCoverBottom, width, iCoverBottom)
    }
  }

  const init = () => {
    getPubKey(function () {
      const playMode = 0 //初始播放模式：0-预览，1-回放
      const snapDir = 'C:\\SnapDir' //抓图存储路径
      const videoDir = 'C:\\VideoDir' //紧急录像或录像剪辑存储路径
      const enableHTTPS = 1 //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
      const encryptedFields = 'secret' //加密字段，默认加密领域为secret
      const showToolbar = 1 //是否显示工具栏，0-不显示，非0-显示
      const showSmart = 1 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
      const buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769' //自定义工具条按钮
      const config = {
        appkey: appkey, //API网关提供的appkey
        secret: setEncrypt(secret), //API网关提供的secret
        ip: ip, //API网关IP地址
        playMode: playMode, //播放模式（决定显示预览还是回放界面）
        port: port, //端口
        snapDir: snapDir, //抓图存储路径
        videoDir: videoDir, //紧急录像或录像剪辑存储路径
        layout: layout, //布局
        enableHTTPS: enableHTTPS, //是否启用HTTPS协议
        encryptedFields: encryptedFields, //加密字段
        showToolbar: showToolbar, //是否显示工具栏
        showSmart: showSmart, //是否显示智能信息
        buttonIDs: buttonIDs, //自定义工具条按钮
      }
      oWebControl
        .JS_RequestInterface({
          funcName: 'init',
          argument: JSON.stringify(config),
        })
        .then(function () {
          const { width, height } = getTargetElWH()
          oWebControl.JS_Resize(width, height) // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
        })
    })
  }

  function uninit() {
    oWebControl
      .JS_RequestInterface({
        funcName: 'uninit',
      })
      .then(function () {
        // console.log(oData)
      })
    if (oWebControl != null) {
      oWebControl.JS_HideWnd() // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
    }
    unResize()
  }

  let resizeObserver: any = null
  const resize = () => {
    const el: any = document.querySelector('#' + szPluginContainer)
    resizeObserver = new ResizeObserver(() => {
      clearTimeout(el.__resizeTimer)
      el.__resizeTimer = setTimeout(() => {
        if (oWebControl) {
          const { width, height } = getTargetElWH()
          oWebControl.JS_Resize(width, height)
          // setWndCover();
        }
      }, 200)
    })
    resizeObserver.observe(el)
  }
  const unResize = () => {
    resizeObserver.disconnect()
  }
  const playItem = (cameraIndexCode:any, wndId:any = 0) => {
    //获取输入的监控点编号值，必填
    const streamMode = 0 //主子码流标识：0-主码流，1-子码流
    const transMode = 1 //传输协议：0-UDP，1-TCP
    const gpuMode = 1 //是否启用GPU硬解，0-不启用，1-启用

    oWebControl.JS_RequestInterface({
      funcName: 'startPreview',
      argument: JSON.stringify({
        cameraIndexCode: cameraIndexCode, //监控点编号
        streamMode: streamMode, //主子码流标识
        transMode: transMode, //传输协议
        gpuMode: gpuMode, //是否开启GPU硬解
        // wndId: wndId                                     //可指定播放窗口
      }),
    })
  }
  const stopAll = () => {
    oWebControl.JS_RequestInterface({
      funcName: 'stopAllPreview',
    })
  }
  const stopItem = (cameraIndexCode:any, wndId:any) => {
    oWebControl.JS_StopPlay({
      funcName: 'stopPlay',
      argument: JSON.stringify({
        cameraIndexCode: cameraIndexCode, // 你的监控点编号
        wndIndex: wndId, // 窗口索引
        wndId: wndId, // 窗口索引
      }),
    })
  }
  return {
    initPlugin,
    playItem,
    stopAll,
    stopItem,
    uninit,
    resize,
  }
}
